package com.framework.modules.job.task.yhbtask;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.framework.entity.ter.TerTerminalInfo;
import com.framework.entity.tran.TranTransactionInfo;
import com.framework.service.LvRateService;
import com.framework.service.TerminalInfoService;
import com.framework.service.yhbservice.*;
import com.framework.utils.DateUtils;
import com.framework.utils.string.StringUtil;
import com.framework.yhbEntity.currentcount.YhbCurrentCount;
import com.framework.yhbEntity.transaction.YhbBenefitDay;
import com.framework.yhbEntity.transaction.YhbBenefitInfo;
import com.framework.yhbEntity.user.YhbUser;
import com.framework.yhbEntity.user.YhbUserTerminalRelation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * 用户宝分润
 */
@Component("yhbBenefitTask")
public class YhbBenefitTask {
    @Autowired
    private YhbUserService yhbUserService;

    @Autowired
    private YhbTransactionService yhbTransactionService;

    @Autowired
    private YhbUserTerminalRelationService yhbUserTerminalRelationService;

    @Autowired
    private LvRateService lvRateService;

    @Autowired
    private YhbBenefitDayService yhbBenefitDayService;

    @Autowired
    private YhbBenefitInfoService yhbBenefitInfoService;

    @Autowired
    private YhbCurrentCountService yhbCurrentCountService;

    @Autowired
    private TerminalInfoService terminalInfoService;

    private Logger logger = LoggerFactory.getLogger(getClass());

    private final BigDecimal divideNum = new BigDecimal("10000");

    public void countYhbBenefit() {

        logger.debug("------用户宝计算分润开始-----");

        Long deptId = 2L;
        //昨天的时间
        Date yesterday = DateUtils.addDateDays(new Date(), -1);
        //所有的用户列表
        List<YhbUser> list = yhbUserService.selectList(new EntityWrapper<YhbUser>().eq("dept_id", deptId));
        for (YhbUser yhbUser : list) {

            String benefitNo = verifyBenefitNo(StringUtil.getDateString(5));

            BigDecimal allTran = new BigDecimal("0.00");
            BigDecimal allAmount = new BigDecimal("0.00");

            //可用sn列表
            List<YhbUserTerminalRelation> rlist = yhbUserTerminalRelationService.selectList(
                    new EntityWrapper<YhbUserTerminalRelation>()
                            .eq("user_id", yhbUser.getUserId())
                            .eq("is_use", 1)
                            .eq("is_del", 0));
            for (YhbUserTerminalRelation relation : rlist) {

                //再次核实机器
                TerTerminalInfo t = terminalInfoService.queryTerminalBySn(relation.getSn());
                if (t.getIsYhbuse().intValue() == 0) {
                    continue;
                }

                //交易列表

                //昨日交易列表
                List<TranTransactionInfo> tranList = yhbTransactionService.selectList(new EntityWrapper<TranTransactionInfo>().eq("sn", relation.getSn()).
                        eq("transaction_date", DateUtils.format(yesterday, DateUtils.DATE_PATTERN)));

                for (TranTransactionInfo info :tranList) {

                    Integer count = yhbTransactionService.queryYhbBenefited(info.getTransactionId());
                    if (count > 0) {
                        continue;
                    }
                    BigDecimal yhbrate;
                    if (t.getTerminalType().intValue() == 10 || t.getTerminalType().intValue() == 11) {
                        yhbrate = getJDPayRate(t.getSn());
                    } else {
                        yhbrate = lvRateService.queryYhbRate(relation.getSn(), 100000L, 1L, info.getTerminalType(), info.getIsVip());
                    }

                    if (yhbrate.compareTo(new BigDecimal("0.00")) == 0) {
                        continue;
                    }


                    BigDecimal amount = info.getAmount().multiply(yhbrate).divide(divideNum);

                    yhbUser.setAvailableAmount(yhbUser.getAvailableAmount().add(amount));
                    yhbUser.setTotalTrade(yhbUser.getTotalTrade().add(info.getAmount()));
                    yhbUser.setTotalAmount(yhbUser.getTotalAmount().add(amount));
                    yhbUserService.updateById(yhbUser);

                    allTran = allTran.add(info.getAmount());
                    allAmount = allAmount.add(amount);

                    YhbBenefitInfo yhbBenefitInfo = new YhbBenefitInfo();
                    yhbBenefitInfo.setAmount(amount);
                    yhbBenefitInfo.setYhbBenefitId(benefitNo);
                    yhbBenefitInfo.setCreateDate(new Date());
                    yhbBenefitInfo.setSn(info.getSn());
                    yhbBenefitInfo.setTran(info.getAmount());
                    yhbBenefitInfo.setTransactionId(info.getTransactionId());
                    yhbBenefitInfoService.insert(yhbBenefitInfo);

                    yhbTransactionService.addIsbenefited(info.getTransactionId());
                }

            }
            if (allTran.compareTo(new BigDecimal("0.00")) == 1) {
                //导入
                YhbBenefitDay day = new YhbBenefitDay();
                day.setAllAmount(allAmount);
                day.setAllTran(allTran);
                day.setBenefitDate(yesterday);
                day.setCreateDate(new Date());
                day.setUserId(yhbUser.getUserId());
                day.setYhbBenefitId(benefitNo);
                yhbBenefitDayService.insert(day);

                //导入流水
                String accountId = StringUtil.getDateString(6);
                YhbCurrentCount yhbCurrentCount = new YhbCurrentCount();
                yhbCurrentCount.setCreateDate(new Date());
                yhbCurrentCount.setIncome(1);
                yhbCurrentCount.setIncomeType(3);
                yhbCurrentCount.setRelationId(benefitNo);
                yhbCurrentCount.setUserId(yhbUser.getUserId());
                yhbCurrentCount.setAmount(allAmount);
                yhbCurrentCount.setMoney(allTran);
                yhbCurrentCount.setIsActivity(0);
                yhbCurrentCount.setAccountId(accountId);
                yhbCurrentCountService.insert(yhbCurrentCount);
            }

        }
        logger.debug("------用户宝计算分润结束-----");

    }

    private String verifyBenefitNo(String benefitNo) {
        YhbBenefitDay t = yhbBenefitDayService.selectById(benefitNo);
        if (t != null) {
            benefitNo = StringUtil.getDateString(5);
            verifyBenefitNo(benefitNo);
        }
        return benefitNo;

    }


    public BigDecimal getJDPayRate(String sn) {
        int count = yhbTransactionService.selectCount(new EntityWrapper<TranTransactionInfo>().eq("sn", sn));
        if (count >= 300) {
            Page<TranTransactionInfo> page = yhbTransactionService.selectPage(new Page<>(0, 300), new EntityWrapper<TranTransactionInfo>().eq("sn", sn)
                    .orderBy("transaction_date", true)
            );
            List<TranTransactionInfo> records = page.getRecords();
            Date transactionDate = records.get(299).getTransactionDate();

            Date date = DateUtils.addDateMonths(transactionDate, 3);

            Date today = new Date();

            if (date.compareTo(today) == 1) {
                return new BigDecimal("0.00");
            } else {
                return new BigDecimal("3.8");
            }
        } else {
            return new BigDecimal("0.00");
        }
    }

}
